package cn.sirun.com.fca.map.view.impl;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.tencent.cloud.iov.flow.presenter.IPresenter;
import com.tencent.cloud.iov.flow.view.IContentViewContainer;
import com.tencent.cloud.iov.router.Router;
import com.tencent.cloud.iov.util.ActivityUtils;
import com.tencent.lbssearch.TencentSearch;
import com.tencent.lbssearch.httpresponse.BaseObject;
import com.tencent.lbssearch.httpresponse.HttpResponseListener;
import com.tencent.lbssearch.object.Location;
import com.tencent.lbssearch.object.param.SearchParam;
import com.tencent.lbssearch.object.param.SuggestionParam;
import com.tencent.lbssearch.object.result.SearchResultObject;
import com.tencent.lbssearch.object.result.SuggestionResultObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import cn.sirun.com.fca.map.R;
import cn.sirun.com.fca.map.adapter.PoiResultAdapter;
import cn.sirun.com.fca.map.adapter.SearchResultAdapter;
import cn.sirun.com.fca.map.constant.MapActivityConst;
import cn.sirun.com.fca.map.listener.MyItemLongClickListener;
import cn.sirun.com.fca.map.model.bean.AddressBean;
import cn.sirun.com.fca.map.uitl.AddressHistoryUtils;


public class SearchMapView extends MapBaseLoadingFlowView {

    private RecyclerView lvdata;
    private PoiResultAdapter poiResultAdapter;
    private EditText etsearch;
    private ImageView iv_close;
    private ImageView iv_goback;
    private AddressBean addressBean;
    private String flg;

    public SearchMapView(Activity activity) {
        super(activity);
    }

    public SearchMapView(Activity activity, IContentViewContainer container) {
        super(activity, container);

    }
    @Override
    public void onCreate() {
        super.onCreate();
        View view = LayoutInflater.from(getContext())
                .inflate(R.layout.map_search_fragment, null, false);
        setContentView(view);
        lvdata = view.findViewById(R.id.lv_map_search_result);
        lvdata.setLayoutManager(new LinearLayoutManager(getContext(),
                LinearLayoutManager.VERTICAL, false));

        etsearch = view.findViewById(R.id.et_map_search);
        etsearch.addTextChangedListener(textWatcher);
        etsearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if(!etsearch.hasFocus()){
                    lvdata.setVisibility(View.GONE);
                }
            }
        });

        iv_close = view.findViewById(R.id.iv_map_search_close);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etsearch.setText("");
            }
        });
        iv_goback = view.findViewById(R.id.iv_map_search_go_back);
        iv_goback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });

        // 获取意图对象获取传递的值
        Intent intent = getActivity().getIntent();
        flg = intent.getStringExtra("set");
        if(TextUtils.isEmpty(flg)){
            flg="set";
        }

    }

    final TextWatcher textWatcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub
            searchPoi(s.toString());
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    };

    /**
     * poi检索
     */
    protected void searchPoi(String keyword) {
        TencentSearch tencentSearch = new TencentSearch(getContext());
        String keyWord = keyword;
        //城市搜索
        SearchParam.Region region = new SearchParam.Region().poi("北京").//设置搜索城市
                autoExtend(false);//设置搜索范围不扩大
        //圆形范围搜索
        Location location1 = new Location().lat(39.984154f).lng(116.307490f);
        SearchParam.Nearby nearBy = new SearchParam.Nearby().point(location1).r(1000);
        //矩形搜索，这里的范围是故宫
        Location location2 = new Location().lat(39.913127f).lng(116.392164f);
        Location location3 = new Location().lat(39.923034f).lng(116.402078f);
        SearchParam.Rectangle rectangle = new SearchParam.Rectangle().point(location2, location3);

        //filter()方法可以设置过滤类别，
        //search接口还提供了排序方式、返回条目数、返回页码具体用法见文档，
        //同时也可以参考官网的webservice对应接口的说明
        SearchParam searchParam = new SearchParam().keyword(keyWord).boundary(region);
        tencentSearch.search(searchParam, new HttpResponseListener() {

            @Override
            public void onFailure(int arg0, String arg1, Throwable arg2) {
                // TODO Auto-generated method stub
//                printResult(arg1);
            }

            @Override
            public void onSuccess(int arg0, BaseObject arg1) {
                // TODO Auto-generated method stub
                if (arg1 == null) {
                    return;
                }
                SearchResultObject obj = (SearchResultObject) arg1;
                if(obj.data == null){
                    lvdata.setVisibility(View.GONE);
                    return;
                }
                if(poiResultAdapter ==null){
                    poiResultAdapter = new PoiResultAdapter(obj.data,getContext());
                    lvdata.setAdapter(poiResultAdapter);
                }else {
                    poiResultAdapter.setCarStatusData(obj.data);
                    poiResultAdapter.notifyDataSetChanged();
                }
                lvdata.setVisibility(View.VISIBLE);
                poiResultAdapter.setListener(new MyItemLongClickListener() {
                    @Override
                    public void onItemLongClick(View view, int postion) {
                        SearchResultObject.SearchResultData obj ;
                        List<AddressBean> addressList= AddressHistoryUtils.getAddressHistoty();
                        obj = poiResultAdapter.getCarStatusData().get(postion);
                        //保存搜索记录
                        addressBean = new AddressBean();
                        addressBean.setName(obj.title);
                        addressBean.setAddress(obj.address);
                        addressBean.setLatitude(obj.location.lat);
                        addressBean.setLongitude(obj.location.lng);
                        if(addressList==null){
                            addressList = new ArrayList<>();
                        }
                        addressList.add(addressBean);
                        AddressHistoryUtils.saveAddressHistory(addressList);

                        etsearch.removeTextChangedListener(textWatcher);
                        CharSequence cs = ((TextView)view.findViewById(R.id.tv_map_result_address)).getText();
                        etsearch.setText(cs);
                        etsearch.setSelection(etsearch.getText().length());
                        lvdata.setVisibility(View.GONE);
                        etsearch.addTextChangedListener(textWatcher);
                        Intent intent = Router.fromPath(MapActivityConst.Path.MAP_SEND_CAR);
                        if(flg.equals("sethome")){
                            intent.putExtra("set","sethome");
                        }else if(flg.equals("setcompany")){
                            intent.putExtra("set","setcompany");
                        } else {
                            intent.putExtra("set","send");
                        }
                        intent.putExtra("addresslat",obj.location.lat+"");
                        intent.putExtra("addresslng",obj.location.lng+"");
                        intent.putExtra("title",obj.title);
                        intent.putExtra("address",obj.address);
                        ActivityUtils.startActivity(getActivity(),intent);
                        getActivity().finish();
                    }
                });
                String result = "搜索poi\n";
                for(SearchResultObject.SearchResultData data : obj.data){
//                    Log.v("SearchDemo","title:"+data.title + ";" + data.address);
//                    result += data.address+"\n";
                }
//                printResult(result);
            }
        });
    }
    @Override
    protected IPresenter createPresenter() {
        return null;
    }

}
